package com.wyf.android.advance.aidl

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.wyf.android.advance.R
import com.wyf.android.basemodule.IAidlTestInterface

class AidlTestActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_aidl_test)

    }

    val conn = AidlServiceConnection()

    fun bindAidl(view: View) {
        val intent = Intent().apply {
            component = ComponentName(
                "com.wyf.android.basemodule",
                "com.wyf.android.basemodule.AidlService"
            )
        }
        bindService(intent, conn, Context.BIND_AUTO_CREATE)
    }

    fun sendMsgByAidl(view: View) {
        //发送数据
        val helloAidl = conn.getAidlInterface()?.helloAidl(1, 2L, true, 3F, 4.0, "hello")
        Log.d("aidl客户端", "onServiceConnected返回数据=${helloAidl}")
    }

    fun unbindAidl(view: View) {
        unbindService(conn)
    }
}

class AidlServiceConnection : ServiceConnection {
    private var asInterface: IAidlTestInterface? = null
    override fun onServiceConnected(name: ComponentName?, serviceIbinder: IBinder?) {
        Log.d("aidl客户端", "onServiceConnected=${name}")
        //拿到服务端的binder对象 通过服务端binder对象创建客户端接口对象，就是一个代理
        asInterface = IAidlTestInterface.Stub.asInterface(serviceIbinder)
    }

    fun getAidlInterface() = asInterface

    override fun onServiceDisconnected(name: ComponentName?) {
        Log.d("aidl客户端", "onServiceDisconnected=${name}")
    }

    override fun onBindingDied(name: ComponentName?) {
        Log.d("aidl客户端", "onBindingDied=${name}")
    }

    override fun onNullBinding(name: ComponentName?) {
        Log.d("aidl客户端", "onNullBinding=${name}")
    }
}